package com.example.algorithm.model;

import lombok.extern.slf4j.Slf4j;

import java.util.StringJoiner;

/**
 * @auth Administrator
 * @create @2024/7/22@20:31
 * @decription
 **/
@Slf4j
public class SingleLinkList {

    private ListNode head;

    private int size;

    public ListNode getHead() {
        return head;
    }

    private  int getSize(){
        return size;
    }

    /**
     * 头插法
     * @param newNode
     * @return
     */
    public void addNodeAtHead(ListNode newNode){ // 添加链表节点
        newNode.next=head;
        head = newNode;
    }

    /**
     * 尾插法
     * @param newNode
     */
    public void addNodeAtTail(ListNode newNode){ // 添加链表节点
        if(head==null){
            head = newNode;
            size=0;
        }else{
            ListNode temp = head;
            while (temp.next != null){ // 当前节点的next为null的时候遍历结束
                temp = temp.next;
            }
            // 将最后一个节点的next指向新节点
            temp.next=newNode;
            size++;
        }
    }

    public boolean hasCycle() {
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (slow==fast) {
                return true;
            }
        }
        return false;
    }

    public void print(ListNode node){
        ListNode curr = node;
        StringJoiner joiner = new StringJoiner(",","[","]");
        while (curr!=null){
            joiner.add(String.valueOf(curr.val));
            curr = curr.next;

        }
        log.info("链表：{}",joiner);

    }

}
